﻿using Rsd.Dudu;
using Rsd.Dudu.Core;
using Rsd.Dudu.Helpers;
using Rsd.Dudu.Web.Core;
using Rsd.Dudu.Web.MVC;
using Rsd.Faith.Core;
using Rsd.Faith.Fiscal.Core;
using Rsd.Faith.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace Rsd.Faith.Fiscal.Services
{
    /// <summary>
    /// 账面数据处理
    /// </summary>
    public class FiscalService : BaseService, IFiscalService
    {
        /// <summary>
        /// 
        /// </summary>
        public override ServiceProxcy Proxcy => ServiceProxcy.Sington;


        /// <summary>
        /// 发票 缴存（住宅）入账(创建、更新 book 和 report）
        /// </summary>
        /// <param name="fapiao"></param>
        /// <returns></returns>
        public int DepositRecordingZZ(IBookService bookService, FiscalPiaoJuXinXiBiaoModel fapiao,BookXiaoQuZongZhangModel b_xiaoqu,BookLouDongMingXiZhangModel b_loudong,BookDanYuanMingXiZhangModel b_danyuan,BookFenHuZhangModel b_fenhu)
        { 
 
            var rs = 0;
            var suoShuQi = fapiao.JiaoNaRiQi.Year.ToString();
            
            var fangwudaima = fapiao.FangWuDaiMa;
            var fangWu = MyType.GetObject<InfoFangWuXinXiBiaoModel>(obj => obj.BianHao == fangwudaima);

            if (fangWu == null)
            {
                ErrorCodesType.F00006.SubmitError(fangwudaima);
                return 0;
            }

            //房屋信息不全
            if (string.IsNullOrEmpty(fangWu.DanYuanHao) || string.IsNullOrEmpty(fangWu.LouDongHao) || string.IsNullOrEmpty(fangWu.XiaoQuBianHao))
            {
                ErrorCodesType.F00016.SubmitError(fangwudaima, fangWu.XiaoQuBianHao == null ? "" : fangWu.XiaoQuBianHao.Trim(), fangWu.LouDongHao == null ? "" : fangWu.LouDongHao.Trim(), fangWu.DanYuanHao == null ? "" : fangWu.DanYuanHao.Trim());
                return 0;
            }
            
            //总账入帐
            rs += this.DepositReportZZ(suoShuQi);

            //分户入帐
            rs += this.DepositRecordingZZ(fapiao, b_fenhu);

            //小区总账入帐
            rs += this.DepositReportZZ(suoShuQi, b_xiaoqu); 

            //楼栋明细入帐
            rs += this.DepositReportZZ(suoShuQi, b_loudong);

            //单元明细入帐
            rs += this.DepositRecordingZZ(suoShuQi, b_danyuan);
             
            return rs;
        }

        /// <summary>
        /// 缴存（住宅）资金总账入账(更新 book 和 report）
        /// </summary>
        /// <param name="suoShuQi"></param>
        /// <returns></returns>
        private int DepositReportZZ(string suoShuQi)
        {

            var dbSession = (IDBSession)this.GetService(typeof(IDBSession), null);
            //资金总账 report__zi_jin_zong_zhang
            var sql_insert = string.Format("insert into report__zi_jin_zong_zhang (id, suo_shu_qi, kai_shi_ri_qi,jie_shu_ri_qi) SELECT '{0}' as 'id','{1}' as 'suo_shu_qi','{1}-01-01' as 'kai_shi_ri_qi','{1}-12-31' as 'jie_shu_ri_qi' where not EXISTS (SELECT 1 from report__zi_jin_zong_zhang where suo_shu_qi = '{1}');", Guid.NewGuid(), suoShuQi);

            var sql_update = string.Format("update report__zi_jin_zong_zhang  as B, (select sum(shi_jiao_jin_e) as 'jiao_cun_jin_e_zz' from fiscal__piao_ju_xin_xi_biao  where suo_shu_qi = '{0}' and zhuang_tai = '{1}' GROUP BY suo_shu_qi ) A  set B.jiao_cun_jin_e_zz = A.jiao_cun_jin_e_zz  where B.suo_shu_qi = '{0}' ;", suoShuQi, FaPiaoZhuangTai.RZ);

            return dbSession.DbService.Execute(new string[] { sql_insert, sql_update });

        }

        /// <summary>
        /// 缴存（住宅）小区总账 入账
        /// </summary>
        /// <param name="suoShuQi"></param>
        /// <param name="xiaoQuBianHao"></param>
        /// <param name="xiaoQuZhangHao"></param>
        /// <returns></returns>
        private int DepositReportZZ(string suoShuQi, BookXiaoQuZongZhangModel account)
        {
            string xiaoQuBianHao = account.XiaoQuBianHao;
            string xiaoQuZhangHao = account.ZhangHuBianHao;
            var _xiaoQuBianHao = xiaoQuBianHao == null ? "" : StringHelper.SqlFilter(xiaoQuBianHao);
            var dbSession = (IDBSession)this.GetService(typeof(IDBSession), null);
            // 小区总账 report__xiao_qu_zhang_mu 
            // 新建属期账目
            var sql_insert_xiaoqu = string.Format("insert into report__xiao_qu_zhang_mu (id,suo_shu_qi,zhang_hu_bian_hao ,xiao_qu_bian_hao ,xiao_qu_ming_cheng) SELECT '{0}' as 'id','{1}' as 'suo_shu_qi','{2}' as 'zhang_hu_bian_hao','{3}' as 'xiao_qu_bian_hao','{4}' as 'xiao_qu_ming_cheng' where not EXISTS (SELECT 1 from report__xiao_qu_zhang_mu where suo_shu_qi = '{1}' and xiao_qu_bian_hao='{3}');", Guid.NewGuid(), suoShuQi, xiaoQuZhangHao, _xiaoQuBianHao, "");
            // 更新 report__xiao_qu_zhang_mu 缴存
            var sql_update_xiaoqu = string.Format("update report__xiao_qu_zhang_mu  as B, (select sum(shi_jiao_jin_e) as 'jiao_cun_jin_e_zz' from fiscal__piao_ju_xin_xi_biao  where suo_shu_qi = '{0}' and xiao_qu_bian_hao='{1}' and zhuang_tai = '{2}'  GROUP BY suo_shu_qi ) A  set B.jiao_cun_jin_e_zz = A.jiao_cun_jin_e_zz where B.suo_shu_qi = '{0}' and xiao_qu_bian_hao='{1}' ;", suoShuQi, _xiaoQuBianHao, FaPiaoZhuangTai.RZ);
            // book__xiao_qu_zong_zhang 缴存更新
            var sql_update_book_xiaoqu = string.Format("update book__xiao_qu_zong_zhang  as B, (select sum(shi_jiao_jin_e) as 'jiao_cun_jin_e_zz' from fiscal__piao_ju_xin_xi_biao  where  xiao_qu_bian_hao='{0}' and zhuang_tai = '{1}') A  set B.jiao_cun_jin_e_zz = A.jiao_cun_jin_e_zz ,B.yu_e_zz = A.jiao_cun_jin_e_zz-B.shi_yong_jin_e_zz where zhang_hu_bian_hao='{2}' ;", _xiaoQuBianHao, FaPiaoZhuangTai.RZ, account.ZhangHuBianHao);

            return dbSession.DbService.Execute(new string[] { sql_insert_xiaoqu, sql_update_xiaoqu, sql_update_book_xiaoqu });
        }

        /// <summary>
        /// 缴存（住宅） 楼栋明细 入账(更新 book 和 report）
        /// </summary>
        /// <param name="suoShuQi"></param>
        /// <param name="account"></param>
        /// <returns></returns>
        private int DepositReportZZ(string suoShuQi, BookLouDongMingXiZhangModel account)
        {
            string xiaoQuBianHao = account.XiaoQuBianHao;
            string louDongHao = account.LouDongHao;
            string louDongZhangHao = account.ZhangHuBianHao;

            var dbSession = (IDBSession)this.GetService(typeof(IDBSession), null);

            var _xiaoQuBianHao = xiaoQuBianHao == null ? "" : StringHelper.SqlFilter(xiaoQuBianHao);
            var _louDongHao = string.IsNullOrEmpty(louDongHao) ? louDongHao : StringHelper.SqlFilter(louDongHao);

            //楼栋明细 report__lou_dong_zhang_mu 
            // 新建属期账目
            var sql_insert_loudong = string.Format("insert into report__lou_dong_zhang_mu (id,suo_shu_qi,zhang_hu_bian_hao ,xiao_qu_bian_hao ,lou_dong_hao) SELECT '{0}','{1}','{2}','{3}','{4}'  where not EXISTS (SELECT 1 from report__lou_dong_zhang_mu where suo_shu_qi = '{1}' and xiao_qu_bian_hao='{3}' and lou_dong_hao='{4}');", Guid.NewGuid(), suoShuQi, louDongZhangHao, _xiaoQuBianHao, _louDongHao);
            // 更新 report__lou_dong_zhang_mu 缴存
            var sql_update_loudong = string.Format("update report__lou_dong_zhang_mu  as B, (select sum(shi_jiao_jin_e) as 'jiao_cun_jin_e_zz' from fiscal__piao_ju_xin_xi_biao c ,info__fang_wu_xin_xi_biao d  where c.suo_shu_qi = '{0}'  and c.zhuang_tai = '{3}' and c.xiao_qu_bian_hao='{1}' and d.lou_dong_hao='{2}' and c.fang_wu_dai_ma = d.bian_hao  GROUP BY c.xiao_qu_bian_hao,c.suo_shu_qi,d.lou_dong_hao ) A  set B.jiao_cun_jin_e_zz = A.jiao_cun_jin_e_zz where B.suo_shu_qi = '{0}' and B.xiao_qu_bian_hao='{1}' and B.lou_dong_hao='{2}';", suoShuQi, _xiaoQuBianHao, _louDongHao, FaPiaoZhuangTai.RZ);

            //更新 book__lou_dong_ming_xi_zhang 缴存
            var sql_update_book_loudong = string.Format("update book__lou_dong_ming_xi_zhang  as B, (select sum(shi_jiao_jin_e) as 'jiao_cun_jin_e_zz' from fiscal__piao_ju_xin_xi_biao c ,info__fang_wu_xin_xi_biao d  where c.zhuang_tai = '{2}' and c.xiao_qu_bian_hao='{0}' and d.lou_dong_hao='{1}' and c.fang_wu_dai_ma = d.bian_hao  GROUP BY c.xiao_qu_bian_hao,d.lou_dong_hao ) A  set B.jiao_cun_jin_e_zz = A.jiao_cun_jin_e_zz ,B.yu_e_zz = A.jiao_cun_jin_e_zz-B.shi_yong_jin_e_zz where B.xiao_qu_bian_hao='{0}' and B.lou_dong_hao='{1}';", _xiaoQuBianHao, _louDongHao, FaPiaoZhuangTai.RZ);

            return dbSession.DbService.Execute(new string[] { sql_insert_loudong, sql_update_loudong, sql_update_book_loudong });

        }

        /// <summary>
        /// 缴存（住宅） 单元明细 入账(更新 book 和 report）
        /// </summary>
        /// <param name="suoShuQi"></param>
        /// <param name="account"></param>
        /// <returns></returns>
        private int DepositRecordingZZ(string suoShuQi, BookDanYuanMingXiZhangModel account)
        {

            string xiaoQuBianHao = account.XiaoQuBianHao;
            string louDongHao = account.LouDongHao;
            string danYuanHao = account.DanYuanHao;
            string danYuanZhangHao = account.ZhangHuBianHao;
            var dbSession = (IDBSession)this.GetService(typeof(IDBSession), null);

            var _xiaoQuBianHao = xiaoQuBianHao == null ? "" : StringHelper.SqlFilter(xiaoQuBianHao);
            var _louDongHao = string.IsNullOrEmpty(louDongHao) ? louDongHao : StringHelper.SqlFilter(louDongHao);
            var _danYuanHao = string.IsNullOrEmpty(danYuanHao) ? danYuanHao : StringHelper.SqlFilter(danYuanHao);

            //单元明细 report__dan_yuan_zhang_mu
            // 新建属期账目
            var sql_insert_danyuan = string.Format("insert into report__dan_yuan_zhang_mu (id,suo_shu_qi,zhang_hu_bian_hao ,xiao_qu_bian_hao ,lou_dong_hao,dan_yuan_hao) SELECT '{0}','{1}','{2}','{3}','{4}','{5}'  where not EXISTS (SELECT 1 from report__dan_yuan_zhang_mu where suo_shu_qi = '{1}' and xiao_qu_bian_hao='{3}' and lou_dong_hao='{4}' and dan_yuan_hao='{5}' );", Guid.NewGuid(), suoShuQi, danYuanZhangHao, _xiaoQuBianHao, _louDongHao, _danYuanHao);
            //更新 report__dan_yuan_zhang_mu 缴存
            var sql_update_danyuan = string.Format("update report__dan_yuan_zhang_mu  as B, (select sum(shi_jiao_jin_e) as 'jiao_cun_jin_e_zz' from fiscal__piao_ju_xin_xi_biao c ,info__fang_wu_xin_xi_biao d  where c.suo_shu_qi = '{0}' and c.xiao_qu_bian_hao = '{1}' and d.xiao_qu_bian_hao='{1}' and d.lou_dong_hao='{2}' and d.dan_yuan_hao = '{3}' and c.fang_wu_dai_ma = d.bian_hao and c.zhuang_tai = '{4}'  GROUP BY c.xiao_qu_bian_hao,c.suo_shu_qi,d.lou_dong_hao,d.dan_yuan_hao  ) A  set B.jiao_cun_jin_e_zz = A.jiao_cun_jin_e_zz where B.suo_shu_qi = '{0}' and xiao_qu_bian_hao='{1}' and lou_dong_hao='{2}' and dan_yuan_hao='{3}' ;", suoShuQi, _xiaoQuBianHao, _louDongHao, _danYuanHao, FaPiaoZhuangTai.RZ);
            //更新 book__dan_yuan_ming_xi_zhang 缴存 
            var sql_update_booK_danyuan = string.Format("update book__dan_yuan_ming_xi_zhang  as B, (select sum(shi_jiao_jin_e) as 'jiao_cun_jin_e_zz' from fiscal__piao_ju_xin_xi_biao c ,info__fang_wu_xin_xi_biao d  where c.xiao_qu_bian_hao='{0}' and d.lou_dong_hao='{1}' and d.dan_yuan_hao = '{2}' and c.fang_wu_dai_ma = d.bian_hao and c.zhuang_tai = '{3}' GROUP BY c.xiao_qu_bian_hao,d.lou_dong_hao,d.dan_yuan_hao  ) A  set B.jiao_cun_jin_e_zz = A.jiao_cun_jin_e_zz ,B.yu_e_zz=A.jiao_cun_jin_e_zz-B.shi_yong_jin_e_zz where xiao_qu_bian_hao='{0}' and lou_dong_hao='{1}' and dan_yuan_hao='{2}' ;",  _xiaoQuBianHao, _louDongHao, _danYuanHao, FaPiaoZhuangTai.RZ);

            return dbSession.DbService.Execute(new string[] { sql_insert_danyuan, sql_update_danyuan, sql_update_booK_danyuan });

        }

        /// <summary>
        /// 分户账 缴存（住宅）入账(更新 book 和 report）
        /// </summary>
        /// <param name="account">分户账号</param>
        /// <returns></returns>
        private int DepositRecordingZZ(FiscalPiaoJuXinXiBiaoModel faPiao, BookFenHuZhangModel account)
        {
            var count = 0;
            string _fenHuZhangHao = account.ZhangHuBianHao;

            var _fangWuDaiMa = faPiao.FangWuDaiMa == null ? "" : StringHelper.SqlFilter(faPiao.FangWuDaiMa);
            var _faPiaoBianHao = faPiao.FaPiaoBianHao == null ? "" : StringHelper.SqlFilter(faPiao.FaPiaoBianHao);
            
            var dbSession = (IDBSession)this.GetService(typeof(IDBSession), null);

            //=================分户账面===================
            //分户 入账流水  book__fen_hu_zhang_liu_shui
            var liuShuiHao = StringHelper.SqlFilter("LS" + _fangWuDaiMa + "JC" + _faPiaoBianHao);
            var sql_insert_book_liushui = string.Format(@"insert into book__fen_hu_zhang_liu_shui (id,zhang_hu_bian_hao,suo_shu_qi,liu_shui_hao,jin_e,yu_e,shou_ru__zhi_chu,ri_qi,zhai_yao,remark) 
        SELECT id, '{0}' as 'zhang_hu_bian_hao',suo_shu_qi as 'suo_shu_qi','{1}' as 'liu_shui_hao',shi_jiao_jin_e,{2} as 'yu_e','收入' as 'shou_ru__zhi_chu',jiao_na_ri_qi as 'ri_qi', '业主缴存(发票号码:{3})' as 'zhai_yao','{4}' as 'remark' from fiscal__piao_ju_xin_xi_biao where fa_piao_bian_hao='{3}' and zhuang_tai = '{5}' and not EXISTS (SELECT 1 from book__fen_hu_zhang_liu_shui where liu_shui_hao = '{1}');", _fenHuZhangHao, liuShuiHao, 0, _faPiaoBianHao, _fangWuDaiMa, FaPiaoZhuangTai.RZ);

            //核算分户账目 缴存 book__fen_hu_zhang
            var sql_update_book = string.Format(@"update book__fen_hu_zhang A,( select sum(shi_jiao_jin_e) as 'jiao_cun_jin_e_zz' from fiscal__piao_ju_xin_xi_biao where fang_wu_dai_ma = '{0}' and zhuang_tai='{1}' ) B set A.jiao_cun_jin_e = B.jiao_cun_jin_e_zz ,A.yu_e = B.jiao_cun_jin_e_zz - A.shi_yong_jin_e where A.zhang_hu_bian_hao = '{2}';", _fangWuDaiMa, FaPiaoZhuangTai.RZ.ToString(), _fenHuZhangHao);

            try
            {
                count += dbSession.DbService.Execute(new string[] { sql_insert_book_liushui, sql_update_book });
            }
            catch (Exception ex)
            {
                ErrorCodesType.F00007.SubmitError(faPiao.FaPiaoBianHao, ex.ToString());
            }

            //=====================分户分期账目====================

            // 分户账目 (缴存) report__fen_hu_zhang_mu{}
            // 新建属期账目
            var sql_insert_report = string.Format("insert into report__fen_hu_zhang_mu{0} (id,suo_shu_qi,zhang_hu_bian_hao ,xiao_qu_bian_hao ,fang_wu_bian_hao) SELECT id,'{0}' as 'suo_shu_qi', zhang_hu_bian_hao,xiao_qu_bian_hao,fang_wu_bian_hao  from book__fen_hu_zhang where zhang_hu_bian_hao='{1}' and not EXISTS (SELECT 1 from report__fen_hu_zhang_mu{0} where zhang_hu_bian_hao = '{1}');", faPiao.SuoShuQi, _fenHuZhangHao);

            // 更新 report__fen_hu_zhang_mu{} 缴存
            var sql_update_report = string.Format("update report__fen_hu_zhang_mu{0} as A, (select fang_wu_dai_ma,sum(shi_jiao_jin_e) as 'jiao_cun_jin_e_zz' from fiscal__piao_ju_xin_xi_biao  where suo_shu_qi = '{0}' and fang_wu_dai_ma ='{1}' and zhuang_tai = '{2}' ) B set A.jiao_cun_jin_e = B.jiao_cun_jin_e_zz where  A.fang_wu_bian_hao = B.fang_wu_dai_ma;", faPiao.SuoShuQi, _fangWuDaiMa, FaPiaoZhuangTai.RZ);

            try
            {
                count += dbSession.DbService.Execute(new string[] { sql_insert_report, sql_update_report });
            }
            catch (Exception ex)
            {
                ErrorCodesType.F00025.SubmitError(faPiao.FaPiaoBianHao, faPiao.SuoShuQi, ex.ToString());
            }

            return count;
        }



        /// <summary>
        /// [未开发]电梯消防设备维修资金缴存 入账
        /// </summary>
        /// <param name="fapiao"></param>
        /// <returns></returns>
        public int DepositRecordingDT( FiscalPiaoJuXinXiDtBiaoModel fapiao)
        {
            throw new NotImplementedException("DepositRecordingDT");

            //var zhaiYao = "开发商缴存（发票号：" + faPiaoBianHao + "）";
            // 入 楼栋帐  收入

            // 入 小区帐  收入

            return 0;
        }

        /// <summary>
        /// 划拨入账：入账  资金总账、小区总账 
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public int FundingRecording(IBookService bookService, UsingZiJinShiYongHuaBoBiaoModel huaBo)
        { 
            var shenQing = MyType.GetObject<UsingZiJinShiYongShenQingBiaoModel>(obj => obj.ShenQingDanHao == huaBo.ShenQingDanHao);
            if (shenQing == null)
            {
                ErrorCodesType.F00018.SubmitError(huaBo.HuaBoBianHao, huaBo.ShenQingDanHao);
                return 0;
            }
            var xiaoqu = MyType.GetObject<InfoXiaoQuWuYeBiaoModel>(obj => obj.BianHao == huaBo.XiaoQuBianHao);

            if (xiaoqu == null)
            {
                //小区不存在
                ErrorCodesType.F00024.SubmitError(huaBo.XiaoQuBianHao);
                return 0;
            }
            var xiaoQuAccount = bookService.NewXiaoQuAccount(huaBo.XiaoQuBianHao, xiaoqu.MingCheng, shenQing.ShenQingRiQi);

            var list_sql = this.FundingRecordingSql(huaBo.XiaoQuBianHao, xiaoQuAccount.ZhangHuBianHao, huaBo.SuoShuQi);
             
           
            var count = 0;
            var dbSession = (IDBSession)this.GetService(typeof(IDBSession), null);

            try
            {
                count = dbSession.DbService.Execute(list_sql);
            }
            catch (System.Exception ex)
            {
                ErrorCodesType.F00030.SubmitError(huaBo.ShenQingDanHao, ex.ToString());
            }
            return count;
        }

        /// <summary>
        /// 划拨入账：入账  资金总账、小区总账 
        /// </summary> 
        /// <param name="xiaoQuBianHao">小区</param>
        /// <param name="suoShuQi">所属期</param> 
        /// <param name="huaBoBianHao">划拨编号</param>
        /// <param name=""></param>
        /// <returns></returns>
        private string[] FundingRecordingSql(string xiaoQuBianHao, string xiaoQuZhangHao, string suoShuQi)
        {
            var _xiaoQuBianHao = StringHelper.SqlFilter(xiaoQuBianHao);
            var list = new List<string>();

            //资金总账 使用  report__zi_jin_zong_zhang
            var sql_insert = string.Format("insert into report__zi_jin_zong_zhang (id, suo_shu_qi, kai_shi_ri_qi,jie_shu_ri_qi) SELECT '{0}' as 'id','{1}' as 'suo_shu_qi','{1}-01-01' as 'kai_shi_ri_qi','{1}-12-31' as 'jie_shu_ri_qi' where not EXISTS (SELECT 1 from report__zi_jin_zong_zhang where suo_shu_qi = '{1}');", Guid.NewGuid(), suoShuQi);
            var sql_update = string.Format(@"update report__zi_jin_zong_zhang a,(select suo_shu_qi, SUM(hua_bo_jin_e) as 'hua_bo_jin_e' from biz__zi_jin_shi_yong_hua_bo_biao where suo_shu_qi ='{0}') b set a.shi_yong_jin_e_zz = b.hua_bo_jin_e where a.suo_shu_qi = '{0}';", suoShuQi);
            list.AddRange(new string[] { sql_insert, sql_update });

            //更新 小区总账 使用   report__xiao_qu_zhang_mu  
            var sql_insert_xiaoqu = string.Format("insert into report__xiao_qu_zhang_mu (id,suo_shu_qi,zhang_hu_bian_hao ,xiao_qu_bian_hao ,xiao_qu_ming_cheng) SELECT '{0}' as 'id','{1}' as 'suo_shu_qi','{2}' as 'zhang_hu_bian_hao','{3}' as 'xiao_qu_bian_hao','{4}' as 'xiao_qu_ming_cheng' where not EXISTS (SELECT 1 from report__xiao_qu_zhang_mu where suo_shu_qi = '{1}' and xiao_qu_bian_hao='{3}');", Guid.NewGuid(), suoShuQi, xiaoQuZhangHao, _xiaoQuBianHao, "");
            var sql_update_xiaoqu = string.Format("update report__xiao_qu_zhang_mu  as B, (select suo_shu_qi, xiao_qu_bian_hao, SUM(hua_bo_jin_e) as 'hua_bo_jin_e' from biz__zi_jin_shi_yong_hua_bo_biao where suo_shu_qi = '{0}' and xiao_qu_bian_hao='{1}' ) A  set B.shi_yong_jin_e_zz = A.hua_bo_jin_e,B.yu_e_zz = B.jiao_cun_jin_e_zz - A.hua_bo_jin_e where B.suo_shu_qi = '{0}' and B.xiao_qu_bian_hao='{1}' ;", suoShuQi, _xiaoQuBianHao);

            //核算 小区总账  使用 book__xiao_qu_zong_zhang
            var sql_update_book_xiaoqu = string.Format("update book__xiao_qu_zong_zhang  as B, (select suo_shu_qi, xiao_qu_bian_hao, SUM(hua_bo_jin_e) as 'hua_bo_jin_e' from biz__zi_jin_shi_yong_hua_bo_biao where xiao_qu_bian_hao='{0}' ) A  set B.shi_yong_jin_e_zz = A.hua_bo_jin_e ,B.yu_e_zz = B.jiao_cun_jin_e_zz - A.hua_bo_jin_e where B.xiao_qu_bian_hao='{0}';", _xiaoQuBianHao);

            list.AddRange(new string[] { sql_insert_xiaoqu, sql_update_xiaoqu, sql_update_book_xiaoqu });

            //*** 此处不核算 ***/
            //** 分摊确认后 核算 楼栋细账 和 单元细帐 支出金额  ***/ 

            return list.ToArray();
        }

        /// <summary>
        /// 分摊确认 【分摊数据中存在 房屋信息不存在情况】
        /// 核算 楼栋明细账 和 单元明细账 支出金额
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public int SharingRecordingMX(IBookService bookService, UsingZiJinShiYongHuaBoBiaoModel huaBo)
        {
            var xiaoQuBianHao = huaBo.XiaoQuBianHao;
            var shenQingDanHao = huaBo.ShenQingDanHao;
            var shenQing = MyType.GetObject<UsingZiJinShiYongShenQingBiaoModel>(obj => obj.ShenQingDanHao == shenQingDanHao);
            if (shenQing == null)
            {
                ErrorCodesType.F00018.SubmitError(huaBo.HuaBoBianHao, huaBo.ShenQingDanHao);
                return 0;
            }

            //分摊数据存在 房屋不存在情况 ，该房尚无缴存信息, 需要先 检查 楼栋和单元账户

            var list_ft = MyType.GetObjects<UsingZiJinShiYongFenTanBiaoModel>(obj => obj.ShenQingDanHao == shenQingDanHao);
            if (list_ft.Length == 0)
            {
                ErrorCodesType.F00036.SubmitError(huaBo.ShenQingDanHao);
                return 0;
            }

            var list_fangwu = new List<string>();
            foreach (var fenTan in list_ft)
            {
                list_fangwu.Add(fenTan.FangWuBianHao);
            }

            //根据 分摊记录 检查  房屋信息 是否存在
            var fangwu_view = MyType.GetDBOperator<InfoFangWuXinXiBiaoModel>().Select(obj => obj.BianHao).Where(obj => list_fangwu.Contains(obj.BianHao)).View("A");
            var fangwu_not_exist_list = MyType.GetReportService<UsingZiJinShiYongFenTanBiaoModel>().Where(obj => obj.ShenQingDanHao == shenQingDanHao).WhereNotIn<string>(obj => obj.FangWuBianHao, fangwu_view).Execute().ConvertToBizObjects<UsingZiJinShiYongFenTanBiaoModel>();
            foreach (var fenTan in fangwu_not_exist_list)
            {
                ErrorCodesType.F00022.SubmitError(shenQingDanHao, fenTan.FangWuBianHao);
            }
            if (fangwu_not_exist_list.Length > 0)
            {
                return 0;
            }

            // 分摊数据 关联房屋信息 查找 单元信息
            var list_danyuan = MyType.GetReportService<InfoFangWuXinXiBiaoModel>()
                .GroupBy(obj => obj.XiaoQuBianHao, "XiaoQuBianHao")
                .GroupBy(obj => obj.LouDongHao, "LouDongHao")
                .GroupBy(obj => obj.DanYuanHao, "DanYuanHao")
                .Where(obj => list_fangwu.Contains(obj.BianHao)).Execute();

               
            //组装sql
            var list_sql = new List<String>();
            
            for (var i = 0; i < list_danyuan.Rows.Count; i++)
            {
                var row = list_danyuan.Rows[i];
                
                var danYuanAccount = bookService.NewDanYuanAccount(row["DanYuanHao"].ToString(), row["LouDongHao"].ToString(), row["XiaoQuBianHao"].ToString(), huaBo.HuaBoRiQi);
               
                //去掉 账户编号参数
                list_sql.AddRange(this.SharingRecordingDYMXSql(huaBo.SuoShuQi, row["XiaoQuBianHao"].ToString(), row["LouDongHao"].ToString(),  danYuanAccount.DanYuanHao, danYuanAccount.ZhangHuBianHao));
            }

            // 分摊数据 关联房屋信息 查找 楼栋信息
            var list_loudong = MyType.GetReportService<InfoFangWuXinXiBiaoModel>()
                .GroupBy(obj => obj.XiaoQuBianHao, "XiaoQuBianHao")
                .GroupBy(obj => obj.LouDongHao, "LouDongHao")
                .Where(obj => list_fangwu.Contains(obj.BianHao)).Execute();

            for (var i = 0; i < list_loudong.Rows.Count; i++)
            {
                var row = list_loudong.Rows[i];
                //  
                var louDongAccount = bookService.NewLouDongAccount(row["LouDongHao"].ToString(), row["XiaoQuBianHao"].ToString(), huaBo.HuaBoRiQi);

                //去掉 账户编号参数
                list_sql.AddRange(this.SharingRecordingLDMXSql(huaBo.SuoShuQi, row["XiaoQuBianHao"].ToString(), row["LouDongHao"].ToString(), louDongAccount.ZhangHuBianHao));
            }
            var count = 0;
            var dbSession = (IDBSession)this.GetService(typeof(IDBSession), null);

            try
            {
                count = dbSession.DbService.Execute(list_sql.ToArray());
            }
            catch (System.Exception ex)
            {
                ErrorCodesType.F00019.SubmitError(shenQingDanHao, ex.ToString());
            }
            return count;
        }

        /// <summary>
        /// 分摊确认 【计算前确保 楼栋账已存在】
        /// 根据分摊明细表 核算 【楼栋明细账】支出金额 
        /// </summary>
        /// <param name="suoShuQi"></param>
        /// <param name="xiaoQuBianHao"></param>
        /// <param name="louDongHao"></param>
        /// <param name="louDongZhangHao"></param>
        /// <param name="danYuanHao"></param>
        /// <param name="danYuanZhangHao"></param>
        /// <returns></returns>
        private string[] SharingRecordingLDMXSql(string suoShuQi, string xiaoQuBianHao, string louDongHao, string louDongZhangHao)
        {
            var _xiaoQuBianHao = StringHelper.SqlFilter(xiaoQuBianHao);
            
            var _louDongHao = string.IsNullOrEmpty(louDongHao) ? louDongHao : StringHelper.SqlFilter(louDongHao);

            var list = new List<string>();

            //根据分摊明细表 更新 小区楼栋 明细账 使用  report__lou_dong_zhang_mu
            var sql_insert_loudong = string.Format(@"insert into report__lou_dong_zhang_mu (id,suo_shu_qi,zhang_hu_bian_hao ,xiao_qu_bian_hao ,lou_dong_hao) SELECT '{0}','{1}','{2}','{3}','{4}'  where not EXISTS (SELECT 1 from report__lou_dong_zhang_mu where suo_shu_qi = '{1}' and xiao_qu_bian_hao='{3}' and lou_dong_hao='{4}');", Guid.NewGuid(), suoShuQi, louDongZhangHao, _xiaoQuBianHao, _louDongHao);
            var sql_update_loudong = string.Format(@"update report__lou_dong_zhang_mu d,(select a.xiao_qu_bian_hao,a.suo_shu_qi,b.lou_dong_hao,sum(a.fen_tan_jin_e) as 'fan_tan_jin_e' from biz__zi_jin_shi_yong_fen_tan_biao a ,info__fang_wu_xin_xi_biao b 
where a.suo_shu_qi = '{0}' and a.fang_wu_bian_hao = b.bian_hao  and a.xiao_qu_bian_hao='{1}' and b.lou_dong_hao ='{2}' ) c set d.shi_yong_jin_e_zz = c.fan_tan_jin_e,d.yu_e_zz = d.jiao_cun_jin_e_zz - c.fan_tan_jin_e where d.suo_shu_qi = c.suo_shu_qi and d.xiao_qu_bian_hao = c.xiao_qu_bian_hao and d.lou_dong_hao = c.lou_dong_hao;", suoShuQi, _xiaoQuBianHao, _louDongHao);

            //根据分摊明细表 核算 小区楼栋 明细户帐  使用 book__lou_dong_ming_xi_zhang 计算前 必须确保账户已存在
            var sql_update_book_loudong = string.Format(@"update book__lou_dong_ming_xi_zhang d,(select a.xiao_qu_bian_hao,a.suo_shu_qi,b.lou_dong_hao,sum(a.fen_tan_jin_e) as 'fan_tan_jin_e' from biz__zi_jin_shi_yong_fen_tan_biao a ,info__fang_wu_xin_xi_biao b 
where a.fang_wu_bian_hao = b.bian_hao  and a.xiao_qu_bian_hao='{0}' and b.lou_dong_hao ='{1}' ) c set d.shi_yong_jin_e_zz = c.fan_tan_jin_e ,d.yu_e_zz=d.jiao_cun_jin_e_zz-c.fan_tan_jin_e where d.xiao_qu_bian_hao =  '{0}' and d.lou_dong_hao =  '{1}';", _xiaoQuBianHao, _louDongHao);

            list.AddRange(new string[] { sql_insert_loudong, sql_update_loudong, sql_update_book_loudong });
             
            return list.ToArray();
        }
       
        /// <summary>
        /// 分摊确认 【计算前确保 单元账已存在】
        ///  根据分摊明细表 核算【单元明细账】 支出金额 
        /// </summary>
        /// <param name="suoShuQi"></param>
        /// <param name="xiaoQuBianHao"></param>
        /// <param name="louDongHao"></param>
        /// <param name="danYuanHao"></param>
        /// <param name="danYuanZhangHao"></param>
        /// <returns></returns>
        private string[] SharingRecordingDYMXSql(string suoShuQi, string xiaoQuBianHao, string louDongHao,string danYuanHao, string danYuanZhangHao)
        {
            var _xiaoQuBianHao = StringHelper.SqlFilter(xiaoQuBianHao);
            var _danYuanHao = string.IsNullOrEmpty(danYuanHao) ? danYuanHao : StringHelper.SqlFilter(danYuanHao);
            var _louDongHao = string.IsNullOrEmpty(louDongHao) ? louDongHao : StringHelper.SqlFilter(louDongHao);

            var list = new List<string>();
 
             
            // 根据分摊明细表 更新 小区单元明细账 使用 report__dan_yuan_zhang_mu 
            var sql_insert_danyuan = string.Format(@"insert into report__dan_yuan_zhang_mu (id,suo_shu_qi,zhang_hu_bian_hao ,xiao_qu_bian_hao ,lou_dong_hao,dan_yuan_hao) SELECT '{0}','{1}','{2}','{3}','{4}','{5}'  where not EXISTS (SELECT 1 from report__dan_yuan_zhang_mu where suo_shu_qi = '{1}' and xiao_qu_bian_hao='{3}' and lou_dong_hao='{4}' and dan_yuan_hao='{5}' );", Guid.NewGuid(), suoShuQi, danYuanZhangHao, _xiaoQuBianHao, _louDongHao, _danYuanHao);

            var sql_update_danyuan = string.Format(@"update report__dan_yuan_zhang_mu d,(select a.xiao_qu_bian_hao,a.suo_shu_qi,b.lou_dong_hao,sum(a.fen_tan_jin_e) as 'fan_tan_jin_e' from biz__zi_jin_shi_yong_fen_tan_biao a ,info__fang_wu_xin_xi_biao b 
where a.suo_shu_qi = '{0}' and a.fang_wu_bian_hao = b.bian_hao and a.xiao_qu_bian_hao ='{1}' and  b.lou_dong_hao = '{2}' and  b.dan_yuan_hao='{3}') c set d.shi_yong_jin_e_zz = c.fan_tan_jin_e ,d.yu_e_zz = d.jiao_cun_jin_e_zz - c.fan_tan_jin_e where d.suo_shu_qi = c.suo_shu_qi and d.xiao_qu_bian_hao = c.xiao_qu_bian_hao and d.lou_dong_hao = c.lou_dong_hao and d.dan_yuan_hao = '{3}';", suoShuQi, _xiaoQuBianHao, _louDongHao, _danYuanHao);

            //根据分摊明细表 核算 小区单元明细户帐  使用   book__lou_dong_ming_xi_zhang  计算前 必须确保账户已存在
            var sql_update_book_danyuan = string.Format(@"update book__dan_yuan_ming_xi_zhang d,(select a.xiao_qu_bian_hao,a.suo_shu_qi,b.lou_dong_hao,sum(a.fen_tan_jin_e) as 'fan_tan_jin_e' from biz__zi_jin_shi_yong_fen_tan_biao a ,info__fang_wu_xin_xi_biao b 
where a.fang_wu_bian_hao = b.bian_hao and a.xiao_qu_bian_hao='{0}' and b.lou_dong_hao ='{1}' ) c set d.shi_yong_jin_e_zz = c.fan_tan_jin_e ,d.yu_e_zz=d.jiao_cun_jin_e_zz-c.fan_tan_jin_e where  d.xiao_qu_bian_hao = '{0}' and d.lou_dong_hao = '{1}' and d.dan_yuan_hao = '{2}';", _xiaoQuBianHao, _louDongHao, _danYuanHao);

            list.AddRange(new string[] { sql_insert_danyuan, sql_update_danyuan, sql_update_book_danyuan });

            return list.ToArray();
        }

        /// <summary>
        /// 分摊入账  【分摊数据中存在 房屋信息不存在情况】
        /// 1:修改分摊数据状态
        /// 2:添加分户账流水 
        /// 3:核算分户账目和账面 的使用金额
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public int SharingRecordingFH(UsingZiJinShiYongHuaBoBiaoModel huaBo)
        {
           
            var shenQingDanHao = huaBo.ShenQingDanHao;
            var shenQing = MyType.GetObject<UsingZiJinShiYongShenQingBiaoModel>(obj => obj.ShenQingDanHao == shenQingDanHao);
            if (shenQing == null)
            {
                ErrorCodesType.F00018.SubmitError(huaBo.HuaBoBianHao, huaBo.ShenQingDanHao);
                return 0;
            }

            var list_ft = MyType.GetObjects<UsingZiJinShiYongFenTanBiaoModel>(obj => obj.ShenQingDanHao == shenQingDanHao);
            if (list_ft.Length == 0)
            {
                ErrorCodesType.F00036.SubmitError(huaBo.ShenQingDanHao);
                return 0;
            }
            var list_fangwu = new List<string>();
            foreach (var fenTan in list_ft)
            {
                if (huaBo.XiaoQuBianHao != fenTan.XiaoQuBianHao)
                {
                    //分摊房屋小区编号 和 申请小区编号不一致
                    ErrorCodesType.F00031.SubmitError(huaBo.HuaBoBianHao,huaBo.XiaoQuBianHao,fenTan.XiaoQuBianHao);
                }
                list_fangwu.Add(fenTan.FangWuBianHao);
            }

            //根据 分摊记录 检查  房屋信息 是否存在
            var fangwu_view = MyType.GetDBOperator<InfoFangWuXinXiBiaoModel>().Select(obj => obj.BianHao).Where(obj => list_fangwu.Contains(obj.BianHao)).View("A");
            var  dt = MyType.GetReportService<UsingZiJinShiYongFenTanBiaoModel>().Where(obj => obj.ShenQingDanHao == shenQingDanHao).WhereNotIn<string>(obj => obj.FangWuBianHao, fangwu_view).Execute();
            var fangwu_not_exist_list = dt.ConvertToBizObjects<UsingZiJinShiYongFenTanBiaoModel>();
            foreach (var fenTan in fangwu_not_exist_list)
            {
                ErrorCodesType.F00022.SubmitError(shenQingDanHao, fenTan.FangWuBianHao);
            }

            //根据 分摊记录 检查 分户信息 是否存在
            var fenhu_view = MyType.GetDBOperator<BookFenHuZhangModel>().Select(obj => obj.FangWuBianHao).Where(obj => list_fangwu.Contains(obj.FangWuBianHao)).View("A");
            var fenhu_not_exist_list = MyType.GetReportService<UsingZiJinShiYongFenTanBiaoModel>().Where(obj => obj.ShenQingDanHao == shenQingDanHao).WhereNotIn<string>(obj => obj.FangWuBianHao, fenhu_view).Execute().ConvertToBizObjects<UsingZiJinShiYongFenTanBiaoModel>();
            foreach (var fenTan in fangwu_not_exist_list)
            {
                ErrorCodesType.F00021.SubmitError(shenQingDanHao, fenTan.XiaoQuBianHao, fenTan.FangWuBianHao);
            }
            if (fangwu_not_exist_list.Length > 0 || fangwu_not_exist_list.Length > 0)
            {
                return 0;
            }

            //组装sql
            var list_sql = new List<String>(); 
            foreach (var fenTan in list_ft)
            {
                list_sql.AddRange(this.SharingRecordingFHSql(fenTan.SuoShuQi, shenQingDanHao, fenTan.FangWuBianHao));
            }

            var count = 0;
            var dbSession = (IDBSession)this.GetService(typeof(IDBSession), null);
            try
            {
                count = dbSession.DbService.Execute(list_sql.ToArray());
            }
            catch (System.Exception ex)
            {
                ErrorCodesType.F00020.SubmitError(shenQingDanHao, ex.ToString());
            }
          
            //修改划拨数据状态为 已入账
            huaBo.ZhuangTai = ZiJinHuaBoZhuangTai.RZ;
            huaBo.SetState(Dudu.BizModel.ObjectStateType.Update);
            MyType.SaveObjects<UsingZiJinShiYongHuaBoBiaoModel>(huaBo);
            return count;
        }

        /// <summary>
        /// 分摊入账 ，【计算前确保 分户账已存在】
        /// 1:修改分摊数据状态
        /// 2:添加分户账流水 
        /// 3:核算分户账目和账面 的使用金额
        /// </summary>
        /// <param name="suoShuQi"></param>
        /// <param name="shenQingDanHao"></param>
        /// <param name="fangWuDaiMa"></param>
        /// <returns></returns>
        private string[] SharingRecordingFHSql(string suoShuQi, string shenQingDanHao, string fangWuDaiMa)
        {
            if (string.IsNullOrEmpty(shenQingDanHao))
            {
                throw new ArgumentNullException("shenQingDanHao");
            }
            var _fangWuDaiMa = StringHelper.SqlFilter(fangWuDaiMa);
            //设置 分摊表 状态
            var sql_update_fen_tan = string.Format(@"update biz__zi_jin_shi_yong_fen_tan_biao set zhuang_tai = '{0}' where shen_qing_dan_hao = '{1}' and fang_wu_bian_hao ='{2}';", FenTanZhuangTai.RZ.ToString(), shenQingDanHao, _fangWuDaiMa);

            //同步 分摊数据 分户账号 流水 支出
            //    
            var sql_insert_fenhu_book = string.Format(@"INSERT INTO book__fen_hu_zhang_liu_shui (id,liu_shui_hao,suo_shu_qi,jin_e,yu_e,shou_ru__zhi_chu,ri_qi,zhai_yao,remark) SELECT id,  CONCAT('LS{0}SY',fang_wu_bian_hao) 'liu_shui_hao',suo_shu_qi,
fen_tan_jin_e,fen_tan_hou_yu_e,'支出',DATE_FORMAT(fen_tan_ri_qi, '%Y-%m-%d'),'使用分摊(申请单号：{0})',fang_wu_bian_hao from biz__zi_jin_shi_yong_fen_tan_biao where shen_qing_dan_hao = '{0}' and zhuang_tai = '{1}' and id not in (SELECT id from book__fen_hu_zhang_liu_shui); ", shenQingDanHao, FenTanZhuangTai.RZ.ToString());

            //同步 流水数据 分户账号 book__fen_hu_zhang_liu_shui
            var sql_update_fenhu_book_liu_shui = @"update book__fen_hu_zhang_liu_shui a ,book__fen_hu_zhang b set a.zhang_hu_bian_hao = b.zhang_hu_bian_hao where b.fang_wu_bian_hao = a.remark and a.zhang_hu_bian_hao is null or a.zhang_hu_bian_hao='';";

            //核算 分户帐(使用) book__fen_hu_zhang
            var sql_update_fenhu_book = string.Format(@"update book__fen_hu_zhang A,( select sum(fen_tan_jin_e) as 'shi_yong_jin_e' from biz__zi_jin_shi_yong_fen_tan_biao where  zhuang_tai = '{0}' and fang_wu_bian_hao ='{1}' ) B set A.shi_yong_jin_e = B.shi_yong_jin_e ,A.yu_e = A.jiao_cun_jin_e - B.shi_yong_jin_e where A.fang_wu_bian_hao = '{1}';", FenTanZhuangTai.RZ.ToString(), _fangWuDaiMa);

            //新建 属期分户账目 report__fen_hu_zhang_mu{0}
            var sql_insert_fenhu_report = string.Format("insert into report__fen_hu_zhang_mu{0} (id,suo_shu_qi,zhang_hu_bian_hao ,xiao_qu_bian_hao ,fang_wu_bian_hao) SELECT id,'{0}' as 'suo_shu_qi', zhang_hu_bian_hao,xiao_qu_bian_hao,fang_wu_bian_hao  from book__fen_hu_zhang where fang_wu_bian_hao='{1}' and not EXISTS (SELECT 1 from report__fen_hu_zhang_mu{0} where fang_wu_bian_hao = '{1}');", suoShuQi, _fangWuDaiMa);

            //核算 分户帐(使用) report__fen_hu_zhang_mu{0}
            var sql_update_fentan_report = string.Format("update report__fen_hu_zhang_mu{0} A,(select fang_wu_bian_hao, sum(fen_tan_jin_e) as 'shi_yong_jin_e' from biz__zi_jin_shi_yong_fen_tan_biao where  suo_shu_qi = '{0}' and fang_wu_bian_hao ='{1}' and zhuang_tai = '{2}' GROUP BY fang_wu_bian_hao  ) B set A.shi_yong_jin_e = B.shi_yong_jin_e ,A.yu_e = A.jiao_cun_jin_e - B.shi_yong_jin_e  where A.fang_wu_bian_hao = B.fang_wu_bian_hao ;", suoShuQi, _fangWuDaiMa, FaPiaoZhuangTai.RZ);

            return new string[] { sql_update_fen_tan, sql_insert_fenhu_book, sql_update_fenhu_book, sql_update_fenhu_book_liu_shui, sql_insert_fenhu_report, sql_update_fentan_report };
           
        }
         
        /// <summary>
        /// 根据分摊明细信息 创建房屋信息 、房屋账户信息
        /// </summary>
        /// <returns></returns>
        public int NewFangWuXinXi(IBookService bookService, UsingZiJinShiYongHuaBoBiaoModel huaBo)
        {

            var shenQingDanHao = huaBo.ShenQingDanHao;
            var shenQing = MyType.GetObject<UsingZiJinShiYongShenQingBiaoModel>(obj => obj.ShenQingDanHao == shenQingDanHao);
            if (shenQing == null)
            {
                ErrorCodesType.F00018.SubmitError(huaBo.HuaBoBianHao, huaBo.ShenQingDanHao);
                return 0;
            }
            var xiaoQuBianHao = huaBo.XiaoQuBianHao;

            var xiaoqu = MyType.GetObject<InfoXiaoQuWuYeBiaoModel>(obj => obj.BianHao == xiaoQuBianHao);

            if (xiaoqu == null)
            {
                //小区不存在
                ErrorCodesType.F00024.SubmitError(huaBo.ShenQingDanHao, xiaoQuBianHao);
                return 0;

            }
            var list_ft = MyType.GetObjects<UsingZiJinShiYongFenTanBiaoModel>(obj => obj.ShenQingDanHao == shenQingDanHao);
            if (list_ft.Length == 0)
            {
                ErrorCodesType.F00036.SubmitError(huaBo.ShenQingDanHao);
                return 0;
            }

            var list_fangwu = new List<string>();
            foreach (var fenTan in list_ft)
            {
                if (huaBo.XiaoQuBianHao != fenTan.XiaoQuBianHao)
                {
                    //分摊房屋小区编号 和 申请小区编号不一致
                    ErrorCodesType.F00031.SubmitError(huaBo.HuaBoBianHao, huaBo.XiaoQuBianHao, fenTan.XiaoQuBianHao);
                }

                list_fangwu.Add(fenTan.FangWuBianHao);
            }

            //检查 分摊记录中不存在的  房屋信息
            var fangwu_list = new List<InfoFangWuXinXiBiaoModel>();

            var fangwu_view = MyType.GetDBOperator<InfoFangWuXinXiBiaoModel>().Select(obj => obj.BianHao).Where(obj => list_fangwu.Contains(obj.BianHao)).View("A");

            var dt = MyType.GetReportService<UsingZiJinShiYongFenTanBiaoModel>()
                .Where(obj => obj.ShenQingDanHao == shenQingDanHao)
                .WhereNotIn<string>(obj => obj.FangWuBianHao, fangwu_view)
                .Execute();

            var fangwu_not_exist_list = dt.ConvertToBizObjects<UsingZiJinShiYongFenTanBiaoModel>();

            foreach (var fenTan in fangwu_not_exist_list)
            {
                var fangwu = new InfoFangWuXinXiBiaoModel();

                fangwu.ZhuangTai = FangWuZhuangTai.YC;
                fangwu.Remark = "根据分摊数据反推房屋信息"; 
                fangwu.YeZhuXingMing = "【来自分摊记录】";
                fangwu.XiaoQuBianHao = fenTan.XiaoQuBianHao;
                fangwu.LouDongHao = "0000";
                fangwu.DanYuanHao = "0000";
                fangwu.JianZhuMianJi = fenTan.JianZhuMianJi;
                fangwu.BianHao = fenTan.FangWuBianHao;
                fangwu.SetState(Dudu.BizModel.ObjectStateType.New);
                fangwu_list.Add(fangwu);
                //创建分户账
                var fangHuAccount = bookService.NewFenHuAccount(fangwu.BianHao, fangwu.XiaoQuBianHao, huaBo.HuaBoRiQi);

                if (fangHuAccount == null)
                {
                    //创建分户账 失败
                    ErrorCodesType.F00032.SubmitError(fangwu.XiaoQuBianHao, fangwu.BianHao);
                }
                else
                {
                    fangwu.ZhangHuBianHao = fangHuAccount.ZhangHuBianHao;
                }
            }

            if (fangwu_list.Count > 0)
            {
                MyType.SaveObjects(fangwu_list.ToArray());
            }
           
            //创建小区账
            var xiaoQuAccount = bookService.NewXiaoQuAccount(xiaoqu.BianHao, xiaoqu.MingCheng, huaBo.HuaBoRiQi);
            if (xiaoQuAccount == null)
            {
                //创建小区账 失败
                ErrorCodesType.F00035.SubmitError(xiaoqu.BianHao);
            }
           
            //创建楼栋账
            var louDongAccount = bookService.NewLouDongAccount("0000", huaBo.XiaoQuBianHao, huaBo.HuaBoRiQi);
            if (xiaoQuAccount == null)
            {
                //创建楼栋账 失败
                ErrorCodesType.F00034.SubmitError(xiaoqu.BianHao,"0000");
            }

            //创建单元账
            var danYuanAccount = bookService.NewDanYuanAccount("0000", "0000", huaBo.XiaoQuBianHao, huaBo.HuaBoRiQi);
            if (xiaoQuAccount == null)
            {
                //创建单元账 失败
                ErrorCodesType.F00033.SubmitError(xiaoqu.BianHao, "0000", "0000");
            }

            return 0;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override dynamic GetMonitorInfo()
        {
            return new DataTable();
        }
    }


}
